import { extToMimeMap } from '@/config';
import { ProductInfo } from '@/lib/dianxiaomi';
import { GigaProductDetialInfo } from '@/lib/giga';
import { compressImage, getFileExtension, getImageSize } from '@/lib/utils';
import { OperationMessage, OperationMessageType } from '@/store/message';
import JSZip from 'jszip';

export function useSave({
  addMessage,
}: {
  addMessage: (message: Omit<OperationMessage, 'id'>) => void;
}) {
  const appConfig = useAppConfig();
  async function saveGigaResource({
    blob,
    skuIdInfo,
    directoryHandle,
    // 是否过滤图像
    filterImage = false,
  }: {
    blob: Blob;
    skuIdInfo: string;
    directoryHandle: FileSystemDirectoryHandle;
    filterImage?: boolean;
  }) {
    const zip = new JSZip();
    const zipBlob = await zip.loadAsync(blob);
    const files = zipBlob.files;
    // console.log(files);
    await Promise.all(
      Object.keys(files).map(async (relativePath) => {
        const blob = await files[relativePath].async('blob');
        relativePath = relativePath.toLowerCase();
        if (relativePath.startsWith('image')) {
          // 如果是图片直接保存到目录下
          const fileName = relativePath.split('/').pop()!;
          if (fileName.match(/\.(jpg|jpeg|png|bmp|webp)$/i)) {
            let imageBlob = blob;
            if (filterImage) {
              // 对图片进行过滤
              const { width, height, image } = await getImageSize(blob);
              // console.log(width, height);
              // if (width !== height) {
              //   addMessage({
              //     category: skuIdInfo,
              //     type: OperationMessageType.verbose,
              //     message: `图片因为宽高不一致被过滤: ${fileName}`,
              //   });
              //   return;
              // }
              imageBlob = await compressImage({
                blob,
                image,
                width: 800,
                height: 800,
                quality: 0.8,
                format: extToMimeMap[getFileExtension(fileName).toLowerCase()],
              });
            }
            const fileHandle = await directoryHandle.getFileHandle(fileName, { create: true });
            const writable = await fileHandle.createWritable();
            writable.write(imageBlob);
            writable.close();
            addMessage({
              category: skuIdInfo,
              type: OperationMessageType.verbose,
              message: `成功保存图片: ${fileName}`,
            });
          }
        }
        if (relativePath.startsWith('file')) {
          // 如果是产品说明那么保存到产品说明目录下
          const fileName = relativePath.split('/').pop()!;
          const dirHandle = await directoryHandle.getDirectoryHandle(
            appConfig.productDetailDirectorname,
            { create: true },
          );
          const fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
          const writable = await fileHandle.createWritable();
          writable.write(blob);
          writable.close();
          addMessage({
            category: skuIdInfo,
            type: OperationMessageType.verbose,
            message: `成功保存产品说明书: ${dirHandle.name + '/' + fileName}`,
          });
        }
        if (relativePath.startsWith('video')) {
          // 如果是视频那么就保存到视频目录下
          const fileName = relativePath.split('/').pop()!;
          const dirHandle = await directoryHandle.getDirectoryHandle(
            appConfig.productVideoDirectorname,
            { create: true },
          );
          const fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
          const writable = await fileHandle.createWritable();
          writable.write(blob);
          writable.close();
          addMessage({
            category: skuIdInfo,
            type: OperationMessageType.verbose,
            message: `成功保存视频 ${dirHandle.name + '/' + fileName}`,
          });
        }
      }),
    );
  }

  async function saveGigaDetailInfo({
    gigaProductDetailInfo,
    skuIdInfoDirectoryHandle,
  }: {
    gigaProductDetailInfo: GigaProductDetialInfo;
    skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
  }) {
    const fileHandle = await skuIdInfoDirectoryHandle.getFileHandle(
      appConfig.gigaProductDetailInfoFilename,
      { create: true },
    );
    const writable = await fileHandle.createWritable();
    await writable.write(JSON.stringify(gigaProductDetailInfo));
    await writable.close();
  }

  return {
    saveGigaResource: useCallback(saveGigaResource, [addMessage, appConfig]),
    saveGigaDetailInfo: useCallback(saveGigaDetailInfo, [appConfig]),
  };
}
